import os
from functools import wraps

from flask import Blueprint

from apps.tools.Result import Result


def to_dict_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if isinstance(result, Result):
            return result.to_dict()
        return result

    return wrapper


def register_routes(app, folder):
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.endswith('.py'):
                module_name = os.path.splitext(file)[0]
                module_path = os.path.join(root, file).replace(os.sep, '.')
                module_path = module_path.replace('.py', '')
                module_path = module_path.replace('/', '.')
                module = __import__(module_path, fromlist=['routes'])
                if hasattr(module, 'routes'):
                    blueprint = Blueprint(module_name, __name__)
                    blueprint.url_prefix = '/'
                    module.routes(blueprint)
                    app.register_blueprint(blueprint, url_prefix=blueprint.url_prefix)


def scan_files_and_register_routes(app, folder):
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.endswith('.py'):
                module_name = os.path.splitext(file)[0]
                module_path = os.path.join(root, file).replace(os.sep, '.')
                module = __import__(module_path, fromlist=[module_name])
                if hasattr(module, 'routes'):
                    blueprint = Blueprint(module_name, __name__)
                    module.routes(blueprint)
                    app.register_blueprint(blueprint, url_prefix='/')
